/*
 * Copyright (C) 2013 47 Degrees, LLC
 *  http://47deg.com
 *  hello@47deg.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.pricy.me;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

//import com.devspark.appmsg.AppMsg;
//import com.firebase.client.DataSnapshot;
//import com.firebase.client.Firebase;
//import com.firebase.client.ValueEventListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.haarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.pricy.me.adapters.NotificationAdapter;
import com.pricy.me.adapters.ProductAdapter;
import com.pricy.me.model.Notification;
import com.pricy.me.model.Product;
import com.pricy.me.model.ProductExtended;
import com.pricy.me.model.User;
import com.pricy.me.swipelistview.SwipeListView;

public class StreamProductsActivity extends ActionItems {
	
    private static final int REQUEST_CODE_SETTINGS = 0;
    private static final int CAMERA_REQUEST = 1888;
    private static final int RESULT_LOAD_IMAGE = 1889;
    private ProductAdapter adapter;
    private List<ProductExtended> data;
    private Date currentDate = null;
    private ListView swipeListView;
    private Button btnLoadMore;
    private ProgressDialog progressDialog;
    private Handler btnHandler;
	private Uri imageFileUri;
	private Bitmap pictureThumb;
	private Handler noDataHandler ;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setTheme(R.style.Theme_Sherlock_Light);
        setContentView(R.layout.product_list_view);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
		        .cacheOnDisc()
		        .build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
		        .defaultDisplayImageOptions(defaultOptions)
		        .build();
		ImageLoader.getInstance().init(config);

        data = new ArrayList<ProductExtended>();

        adapter = new ProductAdapter(this, data);

        swipeListView = (ListView) findViewById(R.id.example_lv_list);
        
        // LoadMore button
        btnLoadMore = new Button(this);
        btnLoadMore.setText("Je veux plus de produits ...");
        // Adding Load More button to lisview at bottom
        swipeListView.addFooterView(btnLoadMore);
        btnLoadMore.setVisibility(View.GONE);
        
        btnLoadMore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new ListAppTask().execute();
			}
		});
        
        
     // Init header
        View header = View.inflate(this, R.layout.stream_header, null);
        Button btnAjouter = (Button) header.findViewById(R.id.btn_ajouter);
        btnAjouter.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final CharSequence[] items = {"Prendre une photo", "Choisir dans ma galerie"};

				AlertDialog.Builder builder = new AlertDialog.Builder(StreamProductsActivity.this);
				builder.setTitle("Ajouter un produit");
				builder.setItems(items, new DialogInterface.OnClickListener() {
				    public void onClick(DialogInterface dialog, int item) {
				         if(item == 0){
				        	 imageFileUri = getContentResolver().insert(
										Media.EXTERNAL_CONTENT_URI, new ContentValues());
								Intent i = new Intent(
										android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
								i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
										imageFileUri);
								
								startActivityForResult(i, CAMERA_REQUEST);
				         }
				         else if(item == 1){
				        	 Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				        	 startActivityForResult(i, RESULT_LOAD_IMAGE);
				         }
				    }
				});
				AlertDialog alert = builder.create();
				alert.show();
				
//				AddProductDialog dialog = new AddProductDialog(StreamProductsActivity.this);
//				dialog.setTitle("Ajouter un produit");
//				dialog.show();
			}
			
			
		});	
        swipeListView.addHeaderView(header);
        
        SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(adapter);
        swingBottomInAnimationAdapter.setAbsListView(swipeListView);
        swipeListView.setAdapter(swingBottomInAnimationAdapter);
        
        
        
        
        
        
//        Firebase ref = new Firebase("https://pricyme.firebaseio.com/user/10/notification/");
//
//        // Read data and react to changes
//        ref.addValueEventListener(new ValueEventListener() {
//
//            @Override
//            public void onDataChange(DataSnapshot snap) {
//                Log.e("FIREBASE", snap.getName() + " -> " + snap.getValue());
//            }
//
//            @Override public void onCancelled() { }
//        });
//     
        
        reload();

        new ListAppTask().execute();

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.loading));
        progressDialog.setCancelable(false);
        progressDialog.show();
        
        btnHandler = new Handler(){
        	@Override
        	public void handleMessage(Message msg) {
        		btnLoadMore.setVisibility(View.GONE);
        	}
        };

        noDataHandler =  new Handler(){
           	@Override
           	public void handleMessage(Message msg) {
           		TextView v = new TextView(StreamProductsActivity.this);
           		 v.setText("Aucune donnée à afficher pour le moment veuillez vérifiez votre connexion internet");
           		swipeListView.addFooterView(v);	
           	}
           };


        
    }

    private void reload() {
//        swipeListView.setSwipeMode(SwipeListView.SWIPE_MODE_RIGHT);
//        swipeListView.setSwipeActionLeft(SwipeListView.SWIPE_ACTION_DISMISS);
//        swipeListView.setSwipeActionRight(SwipeListView.SWIPE_ACTION_REVEAL);
    }

    public int convertDpToPixel(float dp){
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        float px = dp * (metrics.densityDpi/160f);
        return (int) px;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SETTINGS:
                reload();
            case CAMERA_REQUEST:
    		        if (resultCode == RESULT_OK) {  
    		        	
    		        	int dw = 500; // Make it at most 200 pixels wide
    					int dh = 500; // Make it at most 200 pixels tall

    					try {
    						BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
    						bmpFactoryOptions.inJustDecodeBounds = true;
    						Bitmap bmp = BitmapFactory
    								.decodeStream(
    										getContentResolver().openInputStream(
    												imageFileUri), null, bmpFactoryOptions);

    						int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
    								/ (float) dh);
    						int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
    								/ (float) dw);
    						if (heightRatio > 1 && widthRatio > 1) {
    							if (heightRatio > widthRatio) {
    								bmpFactoryOptions.inSampleSize = heightRatio;
    							} else {
    								bmpFactoryOptions.inSampleSize = widthRatio;
    							}
    						}
    						bmpFactoryOptions.inJustDecodeBounds = false;
    						bmp = BitmapFactory
    								.decodeStream(
    										getContentResolver().openInputStream(
    												imageFileUri), null, bmpFactoryOptions);
    						
//    						pictureThumb = (Bitmap) data.getExtras().get(android.provider.MediaStore.EXTRA_OUTPUT);
    						//photo.setImageBitmap(pictureThumb);
    						//picture = bmp;
    						AddProductDialog dialog = new AddProductDialog(StreamProductsActivity.this);
        					dialog.setPhoto(bmp, bmp);
        					dialog.show();
        					
    					} catch (FileNotFoundException e) {
    						Log.v("ERROR", e.toString());
    					}
    		        }  
    		        break;
            case RESULT_LOAD_IMAGE:
            	if (resultCode == RESULT_OK && null != data) {
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };
                    Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    AddProductDialog dialog = new AddProductDialog(StreamProductsActivity.this);
					BitmapFactory.Options options=new BitmapFactory.Options();
					options.inSampleSize = 8;
					Bitmap bmpGallery = BitmapFactory.decodeFile(picturePath, options);
					dialog.setPhoto(bmpGallery, bmpGallery);
					dialog.show();
                }
    		    
        }
    }

    public class ListAppTask extends AsyncTask<Void, Void, List<ProductExtended>> {

        protected List<ProductExtended> doInBackground(Void... args) {
        	Product product = new Product();
        	List<ProductExtended> products;
        	if(currentDate == null){
        		products = product.getLastProducts(getApplicationContext());
        	}
        	else{
        		products = product.getLoadProducts(currentDate,getApplicationContext());
        	}
        	if(!products.isEmpty()) 
        		currentDate = products.get(products.size()-1).getDate();
        	else btnHandler.sendEmptyMessage(0);
        	 if(products.size()==0){
          	   noDataHandler.sendEmptyMessage(0);
             }
              return products;
        }

        protected void onPostExecute(List<ProductExtended> result) {
        	try {
        		data.addAll(result);
                adapter.notifyDataSetChanged();
                if (progressDialog != null) {
                    progressDialog.dismiss();
                    progressDialog = null;
                    btnLoadMore.setVisibility(View.VISIBLE);
                }
            } catch (Exception e) {
                // nothing
            }
        	
            
        }
    }

    public String readFile(String file, Context c) {
		StringBuilder json = new StringBuilder();
		try {
			FileInputStream fis = c.openFileInput(file);
			BufferedReader r = new BufferedReader(new InputStreamReader(fis));
			String line;
			while ((line = r.readLine()) != null) {
			    json.append(line);
			}
			fis.close();
			return json.toString();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}

	@Override
	void actualiser() {
		currentDate = null;
		data = new ArrayList<ProductExtended>();
		progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.loading));
        progressDialog.setCancelable(false);
        progressDialog.show();
		new ListAppTask().execute();
		
	}

	@Override
	int whereami() {
		return STREAM_PRODUCT_ACTIVITY;
	}
}
